/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', "N/http", "N/file"], function (search, record, http, file) {

    function getInputData() {
        return search.create({
            type: 'customrecord_fba_inbound_shipment',
            columns: ['custrecord_inbound_shipmentid',
                'custrecord_inbound_store.custrecord_store_seller_id',
                'custrecord_inbound_boxquantity'],
            filters: [['custrecord_inbound_packagelabel', 'is', '@NONE@']]
        }).run().getRange(0, 30);
    }

    function map(context) {
        var recId = JSON.parse(context.value).id;
        var result = JSON.parse(context.value).values;
        log.debug('result', result);
        var sellerId = result['custrecord_inbound_store.custrecord_store_seller_id'];
        var shipmentId = result['custrecord_inbound_shipmentid'];
        var boxQuantity = result['custrecord_inbound_boxquantity'];
        var request = {
            "sellerId": sellerId,
            "shipmentId": shipmentId,
            "pageType": "PackageLabel_Letter_6",
            "numberOfPackages": parseInt(boxQuantity)
        };
        try {
            var response = http.post({
                url: "http://112.74.55.237:8001/inbound/getPackageLabels",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "*/*"
                },
                body: JSON.stringify(request)
            });
            if (response.code == 200) {
                var responseBody = JSON.parse(response.body);
                log.debug('request', JSON.stringify(request));
                log.debug('response', JSON.parse(response.body));
                var pdfDocument = responseBody.GetPackageLabelsResult.TransportDocument.PdfDocument;
                log.debug({title: 'pdfDocument', details: JSON.stringify(pdfDocument)});
                if (pdfDocument) {
                    var pdfRequest = {};
                    pdfRequest.documentCode = pdfDocument;
                    var pdfResp = http.post({
                        url: "http://112.74.55.237:8001/tools/zipByteArrayFile",
                        headers: {
                            "Content-Type": "application/json",
                            "Accept": "*/*"
                        },
                        body: JSON.stringify(pdfRequest)
                    });
                    if (pdfResp.code == 200) {
                        log.debug({title: 'pdfResp.body', details: JSON.stringify(pdfResp.body)});
                        var responseBody = JSON.parse(pdfResp.body);
                        var fileObj = file.create({
                            name: "Package Label of " + shipmentId + '.pdf',
                            fileType: file.Type.PDF,
                            contents: responseBody.documentCode,
                            description: 'This is a shipping label.',
                            encoding: file.Encoding.UTF8,
                            folder: 202,
                            isOnline: true
                        });
                        var fileId = fileObj.save();
                        record.submitFields({
                            type: 'customrecord_fba_inbound_shipment',
                            id: recId,
                            values: {
                                custrecord_inbound_packagelabel: fileId
                            }
                        });
                    }
                }
            } else {
                throw response.body;
            }
        } catch (e) {
            log.error({title: 'e', details: JSON.stringify(e)});
        }
    }

    function reduce(context) {
    }

    function summarize(summary) {

    }

    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
});